
package com.gcloud.mesh.supplier.service;

import com.gcloud.mesh.asset.dao.DatacenterDao;
import com.gcloud.mesh.asset.entity.DatacenterEntity;
import com.gcloud.mesh.header.exception.AssetErrorCode;
import com.gcloud.mesh.header.exception.BaseException;
import com.gcloud.mesh.header.exception.SupplierErrorCode;
import com.gcloud.mesh.header.msg.supplier.*;
import com.gcloud.mesh.header.vo.supplier.K8sClusterVo;
import com.gcloud.mesh.header.vo.supplier.SupplierVo;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.entity.SupplierEntity;
import com.gcloud.mesh.supplier.enums.SystemType;
import com.gcloud.mesh.utils.SupplierSystemTypeUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
//@CacheConfig(cacheNames = Module.COMPONENT)
@Slf4j
public class SupplierService {

    @Autowired
    private SupplierDao supplierDao;
    
    @Autowired
    private DatacenterDao datacenterDao;

    public void create(CreateSupplierMsg msg) {
        log.info("[{}][Supplier] 开始创建Supplier：{}", msg.getMsgId(), msg);
        synchronized (SupplierService.class) {
        	Map<String, Object> p = new HashMap<String, Object>();
            p.put("datacenterId", msg.getDatacenterId());
            p.put("type", msg.getType());
            p.put("name", msg.getName());
        	SupplierEntity supplierEntity = supplierDao.findOneByProperties(p);
            if (supplierEntity != null) {
                log.error("[{}][Supplier] 创建Supplier失败，名字重复", msg.getMsgId());
                throw new BaseException("190104");
            }
            DatacenterEntity dc = datacenterDao.getById(msg.getDatacenterId());
    		if(dc == null) {
    			throw new BaseException(AssetErrorCode.DATACENTER_NOT_EXIST);
    		}
    		SupplierEntity entity = new SupplierEntity();
            entity.setId(UUID.randomUUID().toString());
            entity.setName(msg.getName());
            if(SystemType.getSystemTypeByName(msg.getType()) == null) {
            	log.error("[{}][Supplier] 创建Supplier失败，该类型不存在", msg.getMsgId());
            	throw new BaseException(SupplierErrorCode.SYSTEM_TYPE_NOT_FOUND);
            }
            entity.setType(msg.getType());
            entity.setDatacenterId(msg.getDatacenterId());
            entity.setInsecureCommand(msg.getInsecureCommand());
            entity.setClusterId(msg.getClusterId());
            entity.setConfig(msg.getConfig());      
            supplierDao.save(entity);
            log.info("[{}][Supplier] 创建Supplier成功，supplierId={}", msg.getMsgId(), entity.getId());
            
        }
    }

    public void delete(DeleteSupplierMsg msg) {
        log.info("[{}][Supplier] 开始删除Supplier：id={}", msg.getMsgId(), msg.getId());
        synchronized (SupplierService.class) {
            if (supplierDao.getById(msg.getId()) == null) {
                log.error("[{}][Supplier] 删除Supplier失败，Supplier不存在", msg.getMsgId());
                throw new BaseException(SupplierErrorCode.SUPPLIER_NOT_FOUND);
            }
            supplierDao.deleteById(msg.getId());
            log.info("[{}][Supplier] 删除Supplier成功", msg.getMsgId());
        }
    }

    public void update(UpdateSupplierMsg msg) {
        log.info("[{}][App] 开始更新Supplier：id={}, name={}", msg.getMsgId(), msg.getId(), msg.getName());
        synchronized (SupplierService.class) {
            SupplierEntity app = supplierDao.getById(msg.getId());
            if (app == null) {
                log.error("[{}][Supplier] 更新Supplier失败，Supplier不存在", msg.getMsgId());
                throw new BaseException(SupplierErrorCode.SUPPLIER_NOT_FOUND);
            }
            List<String> updateFields = new ArrayList<String>();
            if (!StringUtils.equals(app.getName(), msg.getName())) {
                app.setName(msg.getName());
                updateFields.add("name");
            }
            if (!StringUtils.equals(app.getConfig(), msg.getConfig())) {
                app.setConfig(msg.getConfig());
                updateFields.add("config");         
            }
            if(updateFields.size() > 0) {
            	supplierDao.update(app, updateFields);
                log.info("[Supplier] 更新Supplier成功：name={}, config={}", msg.getName(), msg.getConfig());
            }
        }
    }
    
    public SupplierVo get(GetSupplierMsg msg) {
        SupplierEntity app = supplierDao.getById(msg.getId());
        if (app == null) {
            log.error("[{}][Supplier] 更新Supplier失败，Supplier不存在", msg.getMsgId());
            throw new BaseException(SupplierErrorCode.SUPPLIER_NOT_FOUND);
        }
        SupplierVo vo = new SupplierVo();
        BeanUtils.copyProperties(app, vo);
        return vo;
    }
    
    public SupplierVo getByClusterId(String clusterId) {
    	List<SupplierEntity> suppliers = supplierDao.findByProperty("type", SystemType.K8S.getName());
    	SupplierVo vo = null;
    	for(SupplierEntity supplier: suppliers) {
    		K8sClusterVo obj = (K8sClusterVo)SupplierSystemTypeUtil.getByName(supplier.getType(), supplier.getConfig());
    		if(obj != null && obj.getClusterId().equals(clusterId)) {
    			vo = new SupplierVo();
    			BeanUtils.copyProperties(supplier, vo);
    		}
    	}
//    	if(vo == null) {
//    		throw new BaseException(SupplierErrorCode.SUPPLIER_NOT_FOUND);
//    	}
    	return vo;
    }

    public List<SupplierVo> list(ListSuppliersMsg msg) {
        return supplierDao.list(msg.getDatacenterId(), SupplierVo.class);
    }
    
    public List<SupplierEntity> listByType(String type) {
    	if( type != null && SystemType.getSystemTypeByName(type) == null) {
    		log.error("[{}][Supplier] 该类型不存在", type);
    	}
    	return supplierDao.list(type, null, SupplierEntity.class);
    }

    public void createOrUpdate(CreateSupplierMsg msg) {
        log.info("[{}][Supplier] 开始创建Supplier：{}", msg.getMsgId(), msg);
        DatacenterEntity dc = datacenterDao.getById(msg.getDatacenterId());
        if(dc == null) {
            throw new BaseException(AssetErrorCode.DATACENTER_NOT_EXIST);
        }
        SystemType systemTypeByName = SystemType.getSystemTypeByName(msg.getType());
        if( systemTypeByName == null) {
            log.error("[{}][Supplier] 创建Supplier失败，该类型不存在", msg.getMsgId());
            throw new BaseException(SupplierErrorCode.SYSTEM_TYPE_NOT_FOUND);
        }
        synchronized (SupplierService.class) {
        	Map<String, Object> p = new HashMap<String, Object>();
            p.put("datacenterId", msg.getDatacenterId());
            p.put("type", msg.getType());
        	SupplierEntity supplierEntity = supplierDao.findOneByProperties(p);
            if (supplierEntity == null) {
            	create(msg);
            	return;
            }
            UpdateSupplierMsg updateMsg = new UpdateSupplierMsg();
            BeanUtils.copyProperties(msg, updateMsg);
            update(updateMsg);
        }
//            SystemType systemTypeByName = SystemType.getSystemTypeByName(msg.getType());
//            if( systemTypeByName == null) {
//                log.error("[{}][Supplier] 创建Supplier失败，该类型不存在", msg.getMsgId());
//                throw new BaseException(SupplierErrorCode.SYSTEM_TYPE_NOT_FOUND);
//            }
//            Map<String,Object> p = Maps.newHashMap();
//            p.put("datacenterId",msg.getDatacenterId());
////            p.put("type",systemTypeByName.getName());
////            p.put("clusterId",msg.getClusterId());
//            SupplierEntity supplierEntity = supplierDao.findOneByProperties(p);
//            if (supplierEntity!=null) {
//                if(StringUtils.isNotBlank(msg.getInsecureCommand())){
//                    supplierEntity.setInsecureCommand(msg.getInsecureCommand());
//                }
//                supplierEntity.setName(msg.getName());
//                supplierEntity.setConfig(msg.getConfig());
//                supplierEntity.setClusterId(msg.getClusterId());
//                supplierDao.update(supplierEntity);
//                log.info("[{}][Supplier] 更新Supplier成功：name={} , InsecureCommand={}", msg.getMsgId(), msg.getName(), msg.getInsecureCommand());
//                return;
//            }
//
////            for(String config: msg.getConfig()) {
//                SupplierEntity entity = new SupplierEntity();
//                BeanUtils.copyProperties(msg,entity);
//                entity.setId(UUID.randomUUID().toString());
//                entity.setConfig(msg.getConfig());
//                supplierDao.save(entity);
//                log.info("[{}][Supplier] 创建Supplier成功，supplierId={}", msg.getMsgId(), entity.getId());
////            }
//
//        }

    }
}
